<template>
  <!--完成确认弹窗-->
  <px-dialog v-model="visible" title="转审" width="600px" destroy-on-close append-to-body @close="handleCancelAudit">
    <px-form ref="auditRef" :model="auditForm" :rules="rules" label-width="100px">
      <px-form-item label="转审人员" prop="transferId">
        <px-select-v2
          v-model="auditForm.transferId"
          style="width: 100%"
          filterable
          clearable
          :options="approvalList"
          placeholder="请选择转审人"
          @change="approvalIdChange"
        />
      </px-form-item>
      <px-form-item label="转审意见" prop="approvalOpinion">
        <px-input v-model="auditForm.approvalOpinion" type="textarea" placeholder="请输入" />
      </px-form-item>
    </px-form>
    <template #footer>
      <div class="dialog-footer">
        <px-button @click="handleCancelAudit">取消</px-button>
        <px-button type="primary" @click="handleSubmitAuditForm(auditRef)">确认</px-button>
      </div>
    </template>
  </px-dialog>
</template>

<script lang="ts" setup>
import { forwardMaintainList } from "@/api/erc/maintain";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs, watchEffect } from "vue";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["closeDialog", "queryTable"]);
// 父级传过来的值
const props = defineProps(["visible", "taskId", "userInfo"]);

const visible = computed(() => props.visible);

// 表单校验规则
const rules = computed(() => ({
  transferId: [{ required: true, message: "请选择转审人", trigger: ["blur"] }],
  approvalOpinion: [{ required: true, message: "请填写转审意见", trigger: ["blur", "change"] }]
}));

const auditRef = ref();

const state = reactive<Record<string, any>>({
  auditForm: {},
  approvalList: []
});
const { auditForm, approvalList } = toRefs(state);

watchEffect(async () => {
  if (visible.value) {
    const res = await getEmployeeIdAndName(["HSE", "ISEP", "ERC&FP"]);
    const userInfo = JSON.parse(localStorage.getItem("userInfo"));
    approvalList.value = res?.filter(item => item.empNo !== userInfo?.empNo);
  }
});

const handleCancelAudit = () => {
  auditRef.value.resetFields();
  emits("closeDialog");
};

// 获取借用人的名字
const approvalIdChange = val => {
  const arr = approvalList.value.filter(item => {
    return item.value === val;
  });
  if (arr && arr.length > 0) {
    auditForm.value.transferName = arr[0].label;
  }
};
/** 提交按钮 */
const handleSubmitAuditForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      await forwardMaintainList({ busId: props.taskId, ...auditForm.value, operateId: props.userInfo.userId, operateName: props.userInfo.realName });
      PxMessage.success("转审成功");
      handleCancelAudit();
      emits("queryTable");
    }
  });
};
</script>
